<script setup>
import {listenMsg, msgListener, sendMsg} from "./util/message";
import msgRouter from "./util/msgRouter";
import {reactive,onMounted,ref} from "vue";
import {generateUUID} from "./util/msgUtil";

let localUser = localStorage.getItem('user');
if (localUser) {
  localUser = JSON.parse(localUser);
}else {
  localUser = {
    id: generateUUID(),
    displayName: "张三"+Math.ceil(Math.random()*100),
    avatar: "https://img1.baidu.com/it/u=2910066181,3478000399&fm=253&app=53&size=f60,60&n=0&g=0n&f=jpeg&fmt=auto?sec=1702036887&t=3a9b93be4074d64c34322eeb8e0b6380"
  };
}

const user = reactive(localUser);

function handlePullMessages(contact, next, instance) {
    let messages = [];
    let isEnd = false;
    if (messages.length < 10) {
      isEnd = true;
    }
    next(messages, isEnd);
}

function handleSend(message, next) {
  sendMsg(message).then(resp => {
      if (resp === 'ok') {
        next();
      }else {
        next({status:'failed'});
      }
  }).catch(()=>{
    next({status:'failed'});
  });
}

const IMUI = ref(null);
const IMUI_REF = (el) => {
  IMUI.value = el;
}

onMounted(() => {
  msgListener();

  listenMsg(msgRouter(IMUI.value,user));

  sendMsg({
    type: 'launch',
    fromUser: {...user,address: '255.255.255.255'},
  }).catch();
})

</script>

<template>
  <lemon-imui
      :user="user"
      :ref="IMUI_REF"
      @pull-messages="handlePullMessages"
      @send="handleSend"
  />
</template>

<style scoped>

</style>
